package com.glsc.ngateway.common.base.repo.mysql.opmanage.report.basicsettings;

import com.alibaba.fastjson.JSONObject;
import com.glsc.ngateway.common.base.domain.mysql.opmanage.report.basicsettings.AssetPool;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

public interface AssetPoolRepo extends JpaRepository<AssetPool, Long>, JpaSpecificationExecutor<AssetPool> {

    @Transactional
    @Modifying
    @Query(value = "update AssetPool t set t.assetPoolName = :assetPoolName, " +
                          "t.valid = :valid, t.modifier = :modifier, t.modifyTime = :modifyTime, " +
                          "t.remark = :remark where t.assetPoolId = :assetPoolId")
    void updateBaseInfo(@Param("assetPoolId") long assetPoolId, @Param("assetPoolName") String assetPoolName,
                        @Param("valid") Long valid, @Param("modifier") String modifier,
                        @Param("modifyTime") LocalDateTime modifyTime, @Param("remark") String remark);

    @Query(value = "select max(t.assetPoolId) from AssetPool t")
    Long queryMaxId();

    @Query(value = "select * from t_asset_pool t where t.fl_assetpoolid = :assetPoolId", nativeQuery = true)
    AssetPool queryById(@Param("assetPoolId") long assetPoolId);

    @Transactional
    @Modifying
    @Query(value = "delete from AssetPool t where t.assetPoolId = :assetPoolId")
    void removeByAssetPoolId(@Param("assetPoolId") long assetPoolId);

    @Query(value = "select fl_assetpoolid, fc_assetpoolname from glsc_data.t_asset_pool where fl_valid = 1 and " +
            "(:username in ('glscdata', 'admin', 'ops') or fl_assetpoolid in (select t1.fl_assetpoolid from " +
            "glsc_data.t_user_asset_pool t1, glsc_data.t_user t2 where t1.user_id = t2.id and t2.username = :username))", nativeQuery = true)
    List<JSONObject> queryAuthAssetPoolByUsername(@Param("username") String username);
}
